package com.beiding.natgo.controller;

import com.beiding.natgo.server.SessionHolder;
import com.beiding.natgo.server.SessionManager;
import com.beiding.natgo.server.SessionManagerUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
public class ServerController {

    //查询所有使用中的端口
    @GetMapping("/usingPorts")
    public List<Integer> usingPorts() {
        SessionManager sessionManager = SessionManagerUtil.getSessionManager();
        Map<String, SessionHolder> sessionHolderMap = sessionManager.getSessionHolderMap();
        return sessionHolderMap.values().stream().map(SessionHolder::getPort).collect(Collectors.toList());
    }

    //获取端口使用详情
    @GetMapping("/portUseDetails")
    public Map<Integer, Map<String, Object>> portUseDetails() {
        Map<Integer, Map<String, Object>> map = new HashMap<>();
        SessionManager sessionManager = SessionManagerUtil.getSessionManager();
        Map<String, SessionHolder> sessionHolderMap = sessionManager.getSessionHolderMap();
        for (SessionHolder value : sessionHolderMap.values()) {
            Integer port = value.getPort();
            Map<String, Object> userProperties = value.getSession().getUserProperties();
            Map<String, Object> details = new HashMap<>();
            details.put("port", port);
            details.put("userProperties", userProperties);
            details.put("lastHeartbeat", value.getLastHeartBeat());
            map.put(port, details);
        }
        return map;
    }

    //断开连接并暂时禁用端口
    @GetMapping("/stopAndForbiddenPort")
    public void stopAndForbiddenPort(@RequestParam Integer port, Long time) {
        SessionManager sessionManager = SessionManagerUtil.getSessionManager();
        SessionHolder sessionHolder = null;
        for (Map.Entry<String, SessionHolder> entry : sessionManager.getSessionHolderMap().entrySet()) {
            if (entry.getValue().getPort().equals(port)) {
                sessionHolder = entry.getValue();
                break;
            }
        }

        if (sessionHolder != null) {
            sessionManager.remove(sessionHolder.getSession());
        }

        sessionManager.forbiddenPort(port, time);
    }

    //移除端口禁用
    @GetMapping("/removeForbiddenPort")
    public void removeForbiddenPort(@RequestParam Integer port) {
        SessionManager sessionManager = SessionManagerUtil.getSessionManager();
        sessionManager.removeForbiddenPort(port);
    }

    //获取所有已被禁用的端口
    @GetMapping("/forbiddenPorts")
    Set<Integer> ForbiddenPorts(){
        SessionManager sessionManager = SessionManagerUtil.getSessionManager();
        return sessionManager.getForbiddenPorts();
    }

}
